package com.imooc.imoocbilibili.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.imooc.imoocbilibili.mapper.DanmuMapper;
import com.imooc.imoocbilibili.entity.Danmu;
import com.imooc.imoocbilibili.service.DanmuService;

import java.util.ArrayList;
import java.util.List;

@Service("danmuService")
@RequiredArgsConstructor
public class DanmuServiceImpl extends ServiceImpl<DanmuMapper, Danmu> implements DanmuService {
    private final StringRedisTemplate redisTemplate;

    @Override
    public Page<Danmu> queryPage(Integer pageNo, Integer pageSize) {
        Page<Danmu> page = this.page(
                new Page<>(pageNo, pageSize),
                // 拼接查询条件
                new LambdaQueryWrapper<Danmu>()
        );

        return page;
    }

    @Override
    public void saveDanmuToRedis(Danmu danmu) {
        String key = "danmu-video-" + danmu.getVideoid();
        String value = redisTemplate.opsForValue().get(key);
        List<Danmu> danmus = new ArrayList<>();
        if (StrUtil.isNotBlank(value)) {
            danmus = JSONUtil.toList(value, Danmu.class);
        }
        danmus.add(danmu);
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(danmus));
    }

}